package com.house.controller;


import com.house.common.Result;
import com.house.entity.User;
import com.house.service.UserService;
import com.house.util.ResultUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author asus
 * @since 2021-02-28
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;

    @PostMapping("/login")
    public Result login(@RequestBody User user)
    {
        user = userService.login(user);
        if(user != null)
        {
            return ResultUtil.success(200, user);
        }
        else{
            return ResultUtil.failure(500,"登录失败");
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user)
    {
        if(userService.register(user) == 1)
        {
            return ResultUtil.success(205, user);
        }
        else{
            return ResultUtil.failure(505, "用户名已被使用，请检查用户名");
        }
    }

    @PostMapping("/userProfile")
    public Result updateUserInfo(@RequestBody User user)
    {
        user = userService.updateUserInfo(user);
        if(user != null)
        {
            return ResultUtil.success(203, user);
        }
        return ResultUtil.failure(503, null);
    }

    @PostMapping("/modifyPassword")
    public Result modifyPassword(@RequestParam("username") String username, @RequestParam("password1") String password1, @RequestParam("password2") String password2)
    {
        if(userService.updatePassword(username, password1, password2))
        {
            return ResultUtil.success(203, "修改密码成功");
        }
        return ResultUtil.failure(503,"修改密码失败");
    }

    @GetMapping("/getAllUsers/{type}")
    public Result getAllUsers(@PathVariable("type") Integer type)
    {
        List<User> list = userService.getAllUser(type);
        if( list != null)
        {
            return ResultUtil.success(201, list);
        }
        return ResultUtil.failure(501, "查询失败");
    }

    @GetMapping("/getUserByUsername/{username}")
    public Result getUserByUsername(@PathVariable("username") String username)
    {
        User user = userService.getUserByUsernameOrId(username, null);
        if(user != null)
        {
            return ResultUtil.success(201, user);
        }
        return ResultUtil.failure(501, "查询失败");
    }

    @GetMapping("/getUserByUserId/{userId}")
    public Result getUserByUserId(@PathVariable("userId") Integer userId)
    {
        User user = userService.getUserByUsernameOrId(null,userId);
        if(user != null)
        {
            return ResultUtil.success(201, user);
        }

        return ResultUtil.failure(501, "查询失败");
    }

    @PostMapping("/upload")
    public Result upload(@RequestParam(name = "file", required = false) MultipartFile file, @RequestParam("username") String username, HttpServletRequest request) {
        if (file == null) {
            return ResultUtil.failure(0, "请选择要上传的图片", null);
        }
        if (file.getSize() > 1024 * 1024 * 10) {
            return ResultUtil.failure(0, "文件大小不能大于10M", null);
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return ResultUtil.failure(0, "请选择jpg,jpeg,gif,png格式的图片", null);
        }

        String savePath = UPLOAD_FOLDER;
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        //通过UUID生成唯一文件名
//        String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
        String filename = username + ".png";
        try {
            //将文件保存指定目录
            file.transferTo(new File(savePath + filename));
            userService.updateUserAvatar(username, filename);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.failure(0, "保存文件异常", null);
        }
        //返回文件名称
        return ResultUtil.success(300, filename);
    }
}
